package com.handpay.zztong.hp.accountcenter.widget;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.handpay.framework.utils.BitmapLoader.ImageCallback;
import com.handpay.framework.utils.BitmapLoaderNew;
import com.handpay.framework.utils.MyAsyncTask;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.other.activity.FullScreenImageActivty;

import java.lang.ref.WeakReference;

/**
 * @author whyuan 提交照片资料相片的自定义view。需要实现具体业务逻辑
 */

public class ConfirmPhotoView extends RelativeLayout {

    private LayoutInflater mInflater;

    public enum Statu {
        NoUpload, Upload, UploadSuccess, UploadFailed
    }

    private Statu mStatu;
    public boolean isLoadSuccess = false;
    private int mDefaultPicShown;
    private int mDefaultLargeShown;
    private ImageView mIvTip;
    private ImageView mIvPhoto;
    private ImageView mIvUpload;
    private String mOutputFileUri;
    // private Bitmap mBitmap;
    private UploadClickListener mUpListener;
    private Context mcontext;
    ThumbnailImageCallback mImageCallback = new ThumbnailImageCallback(this);

    public ConfirmPhotoView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mcontext = context;
        mInflater = LayoutInflater.from(context);
        mInflater.inflate(R.layout.layout_confirm_photo, this);
        mIvTip = (ImageView) this.findViewById(R.id.tip);
        // 点击右上角。问号的状态，显示默认图片；删除状态，删除当前图片.其他状态点击无效
        mIvTip.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (Statu.NoUpload == mStatu) {
                    Intent intent = new Intent(ConfirmPhotoView.this.getContext(), FullScreenImageActivty.class);
                    intent.putExtra(FullScreenImageActivty.KEY_RES_ID, mDefaultLargeShown);
                    ConfirmPhotoView.this.getContext().startActivity(intent);
                } else if (Statu.Upload == mStatu) {
                    mOutputFileUri = null;
                    mIvPhoto.setImageResource(mDefaultPicShown);
                    mIvUpload.setVisibility(View.VISIBLE);
                    mIvTip.setImageResource(R.drawable.wenhao);
                    mStatu = Statu.NoUpload;
                }
            }
        });
        // 点击上传，进入上传。
        mIvUpload = (ImageView) this.findViewById(R.id.iv_upload);
        mIvUpload.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (null != mUpListener) {
                    mUpListener.onUploadClickListener(ConfirmPhotoView.this);
                }
            }
        });
        // 当里面没图片的时候，不反应。当有图片的时候，进入大图
        mIvPhoto = (ImageView) this.findViewById(R.id.iv_photo);
        mIvPhoto.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(mOutputFileUri)) {
                    Intent intent = new Intent(ConfirmPhotoView.this.getContext(), FullScreenImageActivty.class);
                    intent.putExtra(FullScreenImageActivty.KEY_PIC_URI, mOutputFileUri);
                    ConfirmPhotoView.this.getContext().startActivity(intent);
                }
            }
        });
    }

    public void setOptional(boolean optional) {
        if (optional) {
            this.findViewById(R.id.tv_wenhao).setVisibility(View.GONE);
        } else {
            this.findViewById(R.id.tv_wenhao).setVisibility(View.VISIBLE);
        }
    }

    /**
     * @param contentDes      默认描述
     * @param defaultPicShown 示例图片id
     * @param picUri          如果不为空，表示是带着图片进来的。
     * @param success         和picUri和用，表示这张图片是通过的还是失败的
     * @param uploadListener  用户点击上传，如何操作？
     */
    public void init(String contentDes, int defaultPicShown, int defaultPicLargeShown, String picUri, boolean success, UploadClickListener uploadListener) {
        TextView tvContentDes = (TextView) findViewById(R.id.contentDes);
        tvContentDes.setText(contentDes);
        mDefaultPicShown = defaultPicShown;
        mDefaultLargeShown = defaultPicLargeShown;
        mUpListener = uploadListener;
        mIvUpload.setVisibility(View.VISIBLE);
        if (!TextUtils.isEmpty(picUri)) {
            mIvPhoto.setImageResource(defaultPicShown);
            mOutputFileUri = picUri;
            if (success) {
                mIvTip.setImageResource(R.drawable.success);
                mStatu = Statu.UploadSuccess;
            } else {
                mIvTip.setImageResource(R.drawable.warn);
                mStatu = Statu.UploadFailed;
            }
            // 确保该view的大小不可能为0
            measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            /*if(mcontext!=null&&mcontext instanceof IDCardateActivity){
                BitmapLoader.getInstance(getContext()).asynLoadBitmap(picUri,
						picUri, mImageCallback);
			}else{*/
            BitmapLoaderNew.BitmapLoaderListener listener = new BitmapLoaderNew.BitmapLoaderListener() {
                @Override
                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                    loadedImage = ThumbnailUtils.extractThumbnail(loadedImage, mIvPhoto.getMeasuredWidth(), mIvPhoto.getMeasuredHeight());
                    if (loadedImage == null) {
                        Log.i("result", "loadedImage==null");
                    }
                    isLoadSuccess = true;
                    mIvPhoto.setImageBitmap(loadedImage);
                }
            };
            BitmapLoaderNew.getInstance(getContext()).loadImage(picUri, listener);
//			}
        } else {
            mIvPhoto.setImageResource(defaultPicShown);
            mIvTip.setImageResource(R.drawable.wenhao);
            mStatu = Statu.NoUpload;
        }
    }

    public void init(int current_status, String contentDes, int defaultPicShown, int defaultPicLargeShown, String picUri, int status, UploadClickListener uploadListener) {
        TextView tvContentDes = (TextView) findViewById(R.id.contentDes);
        tvContentDes.setText(contentDes);
        mDefaultPicShown = defaultPicShown;
        mDefaultLargeShown = defaultPicLargeShown;
        mUpListener = uploadListener;
        mIvUpload.setVisibility(View.VISIBLE);
        if (!TextUtils.isEmpty(picUri)) {
            mIvPhoto.setImageResource(defaultPicShown);
            mOutputFileUri = picUri;
            if (status == 0) {//审核中
                mIvTip.setVisibility(View.INVISIBLE);
                mStatu = Statu.Upload;
                mIvUpload.setVisibility(View.INVISIBLE);
            } else if (status == 1) {//审核通过--只有整体审核通过才隐藏图片状态
                mIvTip.setImageResource(R.drawable.success);
                mIvTip.setVisibility(View.VISIBLE);
                if (current_status == 0) {//整体审核通过
                    mIvUpload.setVisibility(View.INVISIBLE);
                    mIvTip.setVisibility(View.INVISIBLE);
                }
                mStatu = Statu.UploadSuccess;
                isLoadSuccess = true;
            } else if (status == 2) {//审核失败
                mIvTip.setImageResource(R.drawable.warn);
                mIvTip.setVisibility(View.VISIBLE);
                mStatu = Statu.UploadFailed;
                mIvUpload.setVisibility(View.VISIBLE);
            }
            // 确保该view的大小不可能为0
            measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            BitmapLoaderNew.BitmapLoaderListener listener = new BitmapLoaderNew.BitmapLoaderListener() {
                @Override
                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                    loadedImage = ThumbnailUtils.extractThumbnail(loadedImage, mIvPhoto.getMeasuredWidth(), mIvPhoto.getMeasuredHeight());
                    if (loadedImage == null) {
                        Log.i("result", "loadedImage==null");
                    }
                    isLoadSuccess = true;
                    mIvPhoto.setImageBitmap(loadedImage);
                }
            };
            BitmapLoaderNew.getInstance(getContext()).loadImage(picUri, listener);
        } else {
            //没有数据 有可能审核中也有可能是待补件
            mIvPhoto.setImageResource(defaultPicShown);
            mIvTip.setImageResource(R.drawable.wenhao);
            mStatu = Statu.NoUpload;
            if (status == 0) {//审核中
                mIvTip.setVisibility(View.INVISIBLE);
                mStatu = Statu.Upload;
                mIvUpload.setVisibility(View.INVISIBLE);
            } else if (current_status == 1 || status == -1) {//特殊转态待补件
                mIvTip.setVisibility(View.VISIBLE);
                mStatu = Statu.NoUpload;
                mIvUpload.setVisibility(View.VISIBLE);
            }
        }
    }

    static class ThumbnailImageCallback implements ImageCallback {
        WeakReference<ConfirmPhotoView> mWR;

        public ThumbnailImageCallback(ConfirmPhotoView v) {
            mWR = new WeakReference<ConfirmPhotoView>(v);
        }

        @Override
        public void imageLoaded(final Bitmap imageDrawable, final String imageUrl) {
            HPLog.i("time", "after loadBitmap:" + SystemClock.elapsedRealtime() + " " + imageUrl);
            ConfirmPhotoView hp = mWR.get();
            // 必须匹配才能把image放入Photo
            if (null != hp && null != imageUrl && imageUrl.equals(hp.mOutputFileUri)) {
                // hp.mBitmap = imageDrawable;
                new MyAsyncTask<Object, Object, Bitmap>() {
                    @Override
                    protected void onPostExecute(Bitmap bitmap) {
                        HPLog.i("time", "after extractThumbnail:" + SystemClock.elapsedRealtime() + " " + imageUrl);
                        ConfirmPhotoView pv = mWR.get();
                        if (null != bitmap && null != pv) {
                            pv.mIvPhoto.setImageBitmap(bitmap);
                            pv.isLoadSuccess = true;
                        }
                    }

                    @Override
                    protected Bitmap doInBackground(Object[] params) {
                        ConfirmPhotoView pv = mWR.get();
                        Bitmap thumbnail = null;
                        if (null != pv) {
                            HPLog.i("time", "before extractThumbnail:" + SystemClock.elapsedRealtime() + " " + imageUrl);
                            thumbnail = ThumbnailUtils.extractThumbnail(imageDrawable, pv.mIvPhoto.getMeasuredWidth(), pv.mIvPhoto.getMeasuredHeight());
                        }
                        return thumbnail;
                    }
                }.execute();
            }
        }
    }

    public void setPic(String uri) {
        mOutputFileUri = uri;
        // 创建thumbnail显示在iv_photo上。并将tip的图标改成删除图标
        HPLog.i("time", "before loadBitmap:" + SystemClock.elapsedRealtime() + uri);
        BitmapLoaderNew.BitmapLoaderListener listener = new BitmapLoaderNew.BitmapLoaderListener() {

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                loadedImage = ThumbnailUtils.extractThumbnail(loadedImage, mIvPhoto.getMeasuredWidth(), mIvPhoto.getMeasuredHeight());
                isLoadSuccess = true;
                mIvPhoto.setImageBitmap(loadedImage);
            }

        };
        BitmapLoaderNew.getInstance(getContext()).loadImage(uri, listener);
        mIvTip.setImageResource(R.drawable.clear);
        mIvTip.setVisibility(View.VISIBLE);
        mIvUpload.setVisibility(View.GONE);
        mStatu = Statu.Upload;
    }

    public String getPicUri() {
        return mOutputFileUri;
    }

    public interface UploadClickListener {
        void onUploadClickListener(ConfirmPhotoView view);
    }

}
